<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 公司印章状态查询 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card
          :bordered="false"
          style="padding-bottom: 5rem"
        >
          <title-name title="基本信息" />
          <custom-form
            :form-list="postCode === 'COAYZGL' ? formListBgr : formList"
            :form="form"
            :edit-model="editModel == 0 ? 'V' : ''"
            @getOption="(name, e) => getOption(name, e)"
          >
            <!--参加人员-->
            <template #personIds>
              <a-tag
                v-for="person in form.personIds"
                :key="person.id"
                :closable="editModel != 0"
                color="#108ee9"
                @close="form.personIds = form.personIds.filter((item) => person.id !== item.id)"
              >
                {{ person.name }}
              </a-tag>
              <a-button
                v-if="editModel != 0"
                icon="plus"
                :class="{ ml12: form.personIds ? form.personIds.length > 0 : false }"
                @click="visible = true"
              >
                添加人员
              </a-button>
            </template>
            <!-- 附件上传 -->
            <template #file>
              <template v-if="editModel != 0">
                <l-table
                  :file-auto-loading="false"
                  business-code="UN09"
                  :upload-arrys.sync="form.file"
                />
                <div class="file_prompt">
                  请上传原件，支持格式：.rar .zip .doc .docx .pdf .jpg .png .mp4 .mov
                </div>
              </template>
              <file-link
                v-else
                :file-list="form.file"
              />
            </template>

            <template #bureauFile>
              <template v-if="editModel != 0">
                <l-table
                  :file-auto-loading="false"
                  business-code="UN09"
                  :upload-arrys.sync="form.bureauFile"
                />
                <div class="file_prompt">
                  请上传原件，支持格式：.rar .zip .doc .docx .pdf .jpg .png .mp4 .mov
                </div>
              </template>
              <file-link
                v-else
                :file-list="form.bureauFile"
              />
            </template>
            <template #otherFile>
              <template v-if="editModel != 0">
                <l-table
                  :file-auto-loading="false"
                  business-code="UN09"
                  :upload-arrys.sync="form.otherFile"
                />
                <div class="file_prompt">
                  请上传原件，支持格式：.rar .zip .doc .docx .pdf .jpg .png .mp4 .mov
                </div>
              </template>
              <file-link
                v-else
                :file-list="form.otherFile"
              />
            </template>
          </custom-form>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div class="btn_box page-btn-right-top">
        <a-button
          v-if="editModel != 0"
          :loading="loadingSub"
          type="primary"
          class="button_right"
          @click="handleSubmit()"
        >
          提交
        </a-button>
        <a-button
          type="primary"
          @click="handleActiveClose"
        > 关闭 </a-button>
      </div>
    </a-form-model>
     
    <SelectPersonModal
      :persons="form.personIds"
      :visible.sync="visible"
    />
  </base-breadcrumb>
</template>

<script>
import { create, update, detail } from '@/api/office/sealManage/companySealStatus' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import { createValidator, isPhone } from '@/utils/regExpression' // 正则校验
import SelectSupevise from '@/components/Select/SelectSupevise'
import SelectUndertaking from '@/components/Select/SelectUndertaking'
import Selector from '@/components/Select/Selector'
import { getEmployeesList } from '@/api/commons.js'
import { getLabels } from '@/api/office/supervise.js'
import { getEmployees } from '@/api/businessAffairs/revenueAndCost'
import moment from 'moment'
import SelectDepart from '@/components/Select/SelectDepart.vue'
import SelectPersonModal from '@/components/SelectPersonModal'
import { getOrgManageList } from '@/api/system/system'

export default {
  extends: new BaseEditPage(),
  components: {
    SelectPersonModal
  },
  data() {
    return {
      loading: false, // 加载控件
      loadingSub: false, // 加载按钮
      visible: false, //人员选择控件
      postCode: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.postCode,
      editModel: this.$route.query.editModel, // 操作状态:0 查看;1 编辑;2 新增
      form: {
        careDepartmentId: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.deptId,
        // careId: JSON.parse(sessionStorage.getItem('ycloud-user_info')).employee.id,
        care: {
          key: JSON.parse(sessionStorage.getItem('ycloud-user_info')).id,
          label: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
          phone: JSON.parse(sessionStorage.getItem('ycloud-user_info')).employee.phone
        },
        phone: JSON.parse(sessionStorage.getItem('ycloud-user_info')).employee.phone,
        sealStatus: {
          key: '',
          label: ''
        }
      }, // 表单
      rules: {
        unit: [{ required: true, message: '请选择单位名称', trigger: 'change' }],
        title: [{ required: true, message: '请输入印章名称', trigger: 'change' }],
        careDepartmentId: [{ required: true, message: '请选择保管部门', trigger: 'change' }],
        care: [{ required: true, message: '请选择保管人', trigger: 'change' }],
        phone: [
          {
            required: true,
            validator: createValidator(isPhone, '请输入正确的手机号码', true),
            trigger: 'change'
          }
        ],
        sealStatusId: [{ required: true, message: '请选择印章状态', trigger: 'change' }],
        borrowTimeRange: [{ required: true, message: '请选择外借时间', trigger: 'change' }],
        file: [{ type: 'array', required: true, message: '请上传局印章使用申请表', trigger: 'blur' }],
        bureauFile: [{ type: 'array', required: true, message: '请上传局印章状态查询', trigger: 'blur' }]
      }, // 校验规则
      init: false, // 初始化控件
      formCode: '' // 形式选中项code
    }
  },
  watch: {
    // 监听附件实现附件校验
    'form.file'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('file')
        })
      }
    },
    // 监听附件实现附件校验
    'form.bureauFile'() {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('bureauFile')
        })
      }
    }
  },

  computed: {
    formListBgr() {
      return [
        {
          type: Selector,
          keyName: 'unit',
          viewName: 'unitName',
          label: '单位名称',
          placeholder: '请选择单位名称',
          attrs: {
            selectType: '12',
            urlType: 'union',
            labelInValue: true
          }
        },
        {
          keyName: 'title',
          viewName: 'title',
          type: 'a-input',
          label: '印章名称',
          ellipsis: true
        },
        {
          keyName: 'careDepartmentId',
          viewName: 'careDepartmentName',
          label: '保管部门',
          type: SelectDepart,
          attr: {
            placeholder: '请选择保管部门'
          },
          ellipsis: true
        },
        {
          keyName: 'care',
          viewName: 'careName',
          label: '保管人',
          type: SelectSupevise,
          placeholder: '请选择保管人',
          attrs: {
            orgId: this.form.careDepartmentId,
            culEdu: true,
            labelInValue: true
          },
          ellipsis: true
        },
        {
          keyName: 'phone',
          viewName: 'phone',
          type: 'a-input',
          label: '联系电话',
          ellipsis: true
        },
        {
          type: Selector,
          keyName: 'sealStatusId',
          viewName: 'statusName',
          label: '印章状态',
          attrs: {
            selectType: '11',
            urlType: 'union',
            // labelInValue: true,
            isDefault: true
          }
        },
        {
          keyName: 'borrowTimeRange',
          viewName: 'borrowTime',
          type: 'a-range-picker',
          placeholder: ['请选择日期', '请选择日期'],
          label: '外借时间',
          hidden: this.form.sealStatus.label !== '外借',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          slot: true,
          keyName: 'file',
          label: '局印章使用申请表',
          span: 24
        },
        {
          slot: true,
          keyName: 'bureauFile',
          label: '局印章状态查询',
          span: 24
        },
        {
          slot: true,
          keyName: 'otherFile',
          label: '其他附件',
          span: 24
        }
      ]
    },
    formList() {
      return [
        {
          type: Selector,
          keyName: 'unit',
          viewName: 'unitName',
          label: '单位名称',
          placeholder: '请选择单位名称',
          attrs: {
            selectType: '12',
            urlType: 'union',
            labelInValue: true
          }
        },
        {
          keyName: 'title',
          viewName: 'title',
          type: 'a-input',
          label: '印章名称',
          ellipsis: true
        },
        {
          keyName: 'careDepartmentId',
          viewName: 'careDepartmentName',
          label: '保管部门',
          type: SelectDepart,
          attr: {
            placeholder: '请选择保管部门'
          },
          ellipsis: true
        },
        {
          type: Selector,
          keyName: 'sealStatusId',
          viewName: 'statusName',
          label: '印章状态',
          attrs: {
            selectType: '11',
            urlType: 'union',
            // labelInValue: true,
            isDefault: true
          }
        },
        {
          keyName: 'borrowTimeRange',
          viewName: 'borrowTime',
          type: 'a-range-picker',
          placeholder: ['请选择日期', '请选择日期'],
          label: '外借时间',
          hidden: this.form.sealStatus.label !== '外借',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          slot: true,
          keyName: 'file',
          label: '局印章使用申请表',
          span: 24
        },
        {
          slot: true,
          keyName: 'bureauFile',
          label: '局印章状态查询',
          span: 24
        },
        {
          slot: true,
          keyName: 'otherFile',
          label: '其他附件',
          span: 24
        }
      ]
    }
  },
  methods: {
    /**
     * 获取选中项
     */
    getOption(name, e) {
      if (e) {
        if (name === 'careId') {
          this.form.phone = e.phone
        } else if (name === 'sealStatusId') {
          this.form.sealStatus = {
            key: e.id,
            label: e.name
          }
        }
      }
    },
    /**
     * 默认层级
     */
    handleLevel() {
      let levelCode = JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.code
      if (levelCode == 'PD') {
        return '项目部'
      } else if (levelCode == 'BC') {
        return '分公司'
      } else if (levelCode == 'CO') {
        return '公司'
      }
    },
    /**
     * 校验表单
     */
    handleSubmit() {
      // 提交表单
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          this.handleSubmitApi()
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    },
    /**
     * 提交表单
     */
    handleSubmitApi() {
      let that = this
      let api = [update, create][that.editModel - 1] // 根据操作切换url地址
      that.loading = true
      that.loadingSub = true
      let formData = that.$clone(that.form)
      let form = {
        ...formData,
        unitId: formData.unit.key,
        careId: formData.care.key,
        borrowStartTime: formData.borrowTimeRange ? formData.borrowTimeRange[0] : '',
        borrowEndTime: formData.borrowTimeRange ? formData.borrowTimeRange[1] : '',
        orgId: JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.id,
        fileId: formData.file
          ? formData.file
              .map((item) => {
                return item.commonId
              })
              .toString()
          : '', //上传文件id的数组转字符串
        bureauFileId: formData.bureauFile
          ? formData.bureauFile
              .map((item) => {
                return item.commonId
              })
              .toString()
          : '', //上传文件id的数组转字符串
        otherFileId: formData.otherFile
          ? formData.otherFile
              .map((item) => {
                return item.commonId
              })
              .toString()
          : '' //上传文件id的数组转字符串
      }
      api(form)
        .then(() => {
          that.loading = false
          that.$message.success('提交成功！')
          that.$multiTab.close()
        })
        .catch(() => {
          that.loading = false
        })
    }
  },
  mounted() {
    this.$route.meta.title = ['公司印章状态查看', '公司印章状态编辑', '公司印章状态新增'][this.editModel]
    /**
     * 不为添加时请求详情
     * */
    if (this.editModel != 2) {
      this.loading = true
      detail(this.id)
        .then((res) => {
          this.loading = false
          this.form = {
            ...res.data,
            unit: {
              key: res.data.unitId,
              label: res.data.unitName
            },
            care: {
              key: res.data.careId,
              label: res.data.careName
            },
            sealStatus: {
              key: res.data.sealStatusId,
              label: res.data.statusName
            },
            file: res.data.fileInfoVOS,
            bureauFile: res.data.bureauFileInfoList,
            otherFile: res.data.otherFileInfoList,
            borrowTimeRange: [res.data.borrowStartTime, res.data.borrowEndTime]
          }
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      this.$nextTick(() => {
        this.init = true
      })
    }
  }
}
</script>

<style lang="less" scoped>
.file_prompt {
  color: #999;
}
</style>
